<?php

namespace Admin\Model;

/**
 * Description of GoodsModel
 *
 * @author 阿明 symphp@foxmail.com
 */
class GoodsModel extends \Think\Model {

    /**
     * * 1.商品名称不能为空
     * 2.商品的库存不能为空
     * 3.商品的价格不能为空
     * 4.排序不大于127
     * @var type 
     */
    protected $_validate = array(
        array('name', 'require', '商品名称不能为空', self::EXISTS_VALIDATE, '', self::MODEL_INSERT),
        array('stock', 'require', '商品库存不能为空', self::EXISTS_VALIDATE, '', self::MODEL_INSERT),
        array('shop_price', 'require', '商品价格不能为空', self::EXISTS_VALIDATE, '', self::MODEL_INSERT),
        array('sort','1,127','排序范围出错',2,'length',self::MODEL_INSERT)
    );

    /**
     * 自动完成,在插入的时候将商品状态执行按位或
     * 添加的时间应当是当前时间
     * @var type 
     */
    protected $_auto = array(
        array('goods_status', 'array_sum', self::MODEL_INSERT, 'function'),
        array('inputtime', NOW_TIME, self::MODEL_INSERT),
    );

    /**
     * 添加普通数据
     */
    public function goodsAdd() {
        //传过来有id,不删除主键就报错
        unset($this->data['id']);
        //保存货号
        $this->calc_sn();
        //保存基本信息
        if(($goods_id = $this->add()) === false){
            return false;
        }else{
            //保存详细描述
            //有goods_id执行添加内容
            if($this->_save_goods_content($goods_id) === false){
                $this->error = '保存商品详情出错';
                return false;
            };
        }
        //保存图片信息
        if($this->_save_gallery($goods_id)===false){
            $this->error('保存图片出错');
            return false;
        };
        return true;
    }

    /**
     * 自动计算货号方法
     */
    private function calc_sn() {
        $sn = $this->data['sn'];
        //得到当前日期
        $day = date('ymd');
        if (empty($sn)) {
            //如果没传递货号就生成货号
            //创建表记录每天添加的条数,并用当前时间查询
            $goods_count_model = D('GoodsDayCount');
            if (!($goods_count_model->getFieldByDay($day, 'count'))) {
                $count = 1;
                //构造数据
                $data = array(
                    'day' => $day,
                    'count' => $count,
                );
                //添加数据
                if ($goods_count_model->add($data) === FALSE) {
                    $this->error('添加货号失败');
                };
            } else {
                $count++;
                //给某个字段在原的基础上+1
                $goods_count_model->where(array('day' => $day))->setInc('count', 1);
            }
        }
        //如果有货号添加
        return $this->data['sn'] = 'SN' . $day . str_pad($count, 5, '0', STR_PAD_LEFT);
    }

    /**
     * 分页
     */

    /**
     * 要求不使用数组函数,进行数组合并,要求如果元素键名冲突,就以第一个为准
     * @param array $cond
     * @return type
     */
    public function getPageResult(array $cond = array()) {
        $cond = $cond + array(
            'status' => 1,
        );
        //获取总行数
        $count = $this->where($cond)->count();
        //获取页尺寸
        $size = C('PAGE_SIZE');
        $page_obj = new \Think\Page($count, $size);
        $page_obj->setConfig('theme', C('PAGE_THEME'));
        $page_html = $page_obj->show();
        $rows = $this->where($cond)->page(I('get.p'), $size)->select();
        foreach ($rows as $key => $value) {
            $rows[$key]['is_best'] = $value['goods_status'] & 1 ? 1 : 0;
            $rows[$key]['is_new'] = $value['goods_status'] & 2 ? 1 : 0;
            $rows[$key]['is_hot'] = $value['goods_status'] & 4 ? 1 : 0;
        }
        return array(
            'rows' => $rows,
            'page_html' => $page_html,
        );
    }

    /**
     * 商品编辑
     */
    public function getGoodsInfo($id) {
        //条件
        $cond = array(
            'status' => 1,
        );
        $row = $this->where($cond)->find($id);
        if ($row == null) {
            $this->error = '商品不存在';
            return false;
        }else{
            //获取商品详情
            $content = D('GoodsIntro')->field('content')->find($id)['content'];
            $row['content'] = $content;
            //由于goods_status是数组,我们应该处理了返回给控制器
            $tmp_status          = $row['goods_status'];
            $row['goods_status'] = array();
            if ($tmp_status & 1) {
                $row['goods_status'][] = 1;
            }
            if ($tmp_status & 2) {
                $row['goods_status'][] = 2;
            }
            if ($tmp_status & 4) {
                $row['goods_status'][] = 4;
            }
            $row['goods_status'] = json_encode($row['goods_status']);
            //获取图片信息
            $row['paths'] = D('GoodsGallery')->where(array('goods_id'=>$id))->select();
            //返回最终值
            return $row;
            }
    }
    
    /**
     * 保存内容
     * @param type $goods_id
     * @return type
     */
    public function _save_goods_content($goods_id,$is_new = true){
        //获取到content内容
        $content = I('post.content','',false);
        //将数据存入数据库
       $data = array(
           'goods_id'=>$goods_id,
           'content'=>$content,
       );
       if($is_new){
           return  D('GoodsIntro')->add($data);
       }else{
           return D('GoodsIntro')->save($data);
       }
    }
    
    /**
     * 更新商品
     * @return boolean
     */
    public function updateGoods(){
        //1.保存基本信息
        $request_data = $this->data;
        if($this->save($request_data)===false){
            return false;  
        };
        //2.保存content信息
        if($this->_save_goods_content($request_data['id'],FALSE)===false){
            $this->error = '保存商品详细描述失败';
            return false;
        }
    }
    
    /**
     * 逻辑删除
     * @param type $id
     */
    public function getDelete($id){
        $fond = array(
          'status'=>-1 ,
           'name'=> array('exp', "CONCAT(name,'_del')"),
        );
        return $this->where(array('id'=>$id))->setField($fond);
    }
    
    private function _save_gallery($goods_id){
        $paths = I('post.path');
        if(!$paths){
            return true;
        }
        $data = array();
        //遍历图片
        foreach ($paths as $path) {
            $data[] = array(
                'goods_id' => $goods_id,
                'path' => $path
            );
        }
        //实例化模型
        $goods_gallery = D('goodsGallery');
        dump($goods_gallery->addAll($data));
    }
    
    /**
     * 用于获取分类 供货商 品牌的名称
     */
    public function getTableInfo(){
        //获取分类的数据
        $supplier = D('supplier')->where(array('status'=>1))->getField('id,name');
        //获取供货商数据
        $goodsCategory = D('GoodsCategory')->where(array('status'=>1))->getField('id,name');
        //获取品牌数据
        $brand = D('brand')->where(array('status'=>1))->getField('id,name');
        $getTableInfo = array(
            'supplier'=>$supplier,
            'goodsCategory'=>$goodsCategory,
            'brand'=>$brand,
        );
        
        return $getTableInfo;
    }
    
    //商品状态
    public $goods_status = array(
        1=>'精品',
        2=>'新品',
        4=>'热销',
    );
    
    //商品售卖状态
    public $is_on_sales = array(
        1=>'上架',
        0=>'下架',
    );
    
}
